use BestellungenDB

IF OBJECT_ID ('dbo.createDefaultBestellung','TR') IS NOT NULL
   DROP TRIGGER dbo.createDefaultBestellung
GO
CREATE TRIGGER createDefaultBestellung ON dbo.Kunden
AFTER INSERT
AS
DECLARE @currentMaxBestellungID int, @newBestellungID int, @customerID int

SET @currentMaxBestellungID = (SELECT MAX(id) FROM dbo.Bestellungen)
SET @newBestellungID = @currentMaxBestellungID +1

DECLARE new_customers_cursor CURSOR FOR 
SELECT  k.ID
FROM dbo.Kunden k INNER JOIN inserted i ON k.ID = i.ID

OPEN new_customers_cursor
FETCH NEXT FROM new_customers_cursor
INTO @customerID

WHILE @@FETCH_STATUS = 0
	BEGIN
	INSERT INTO dbo.Bestellungen (ID, Kunde, Datum)	
				VALUES (@newBestellungID, @customerID ,GETDATE()) 
	SET @newBestellungID = @newBestellungID + 1
	FETCH NEXT FROM new_customers_cursor
	INTO @customerID
	END

CLOSE new_customers_cursor
DEALLOCATE new_customers_cursor
